import { GetUserInfo, UserSharePoster } from '@/api/user';
import { Button, Loading } from '@antmjs/vantui';
import { Image, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useRequest } from 'taro-hooks';

export default function Page() {
  const { data: user } = useRequest(GetUserInfo);
  const { data: poster, loading } = useRequest(
    () =>
      UserSharePoster({
        page: 'pages/login/share',
        scene: `?refer_code=${user?.refer_code || ''}`,
      }),
    {
      ready: user?.refer_code ? true : false,
    }
  );

  return (
    <View
      className=' min-h-screen relative overflow-hidden bg-center bg-cover flex flex-col items-center pt-[230px]'
      style={{
        backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/bg4.jpg)`,
      }}
    >
      <View className='w-[670px] h-[656px] relative'>
        {loading && (
          <Loading className=' absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2' />
        )}
        <Image src={poster} className=' w-full h-full block' />
      </View>
      <Button
        disabled={loading}
        className=' text-primary bg-white mt-[160px] w-[670px]'
        block
        size='large'
        onClick={async () => {
          Taro.showLoading({ title: '保存中' });
          const { tempFilePath } = await Taro.downloadFile({
            url: poster,
          });

          Taro.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            complete: function () {
              Taro.hideLoading();
            },
            success() {
              Taro.showToast({ title: '保存成功' });
            },
            fail() {
              Taro.showModal({
                title: '保存失败',
                content: `图片保存失败，原因：您取消了保存或者是没有保存权限，请检查设置是否打开了对应的权限`,
                confirmText: '去设置',
                success: ({ confirm }) => {
                  if (confirm) {
                    Taro.openSetting();
                  }
                },
              });
            },
          });
        }}
      >
        保存海报
      </Button>
    </View>
  );
}
